package com.kye.express.business.vipshop;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.afollestad.materialdialogs.MaterialDialog;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.verification.ExchangeVerificationService;
import com.kye.express.business.vipshop.model.VipExchangeMoneyModel;
import com.kye.express.business.vipshop.viewbinder.VipExchangeViewBinder;
import com.kye.express.business.web.KyeWebActivity;
import com.kye.express.databinding.ActivityVipShopExchangeBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.user.User;
import com.kye.model.bean.vip.VipExchangeResultBean;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class VipExchangeActivity extends BaseToolbarActivity implements VipExchangeConstract.VipExchangeView, VipExchangeViewBinder.OnItemListener, ExchangeVerificationService.OnVerificationCheckListener, ExchangeVerificationService.OnVerificationOptionByAutoSendListener, ExchangeVerificationService.OnVerificationOptionByPictureSmsListener {

    private final String TAG_VIP_SELECTED_MONEY_TYPE = "TAG_VIP_SELECTED_MONEY_TYPE";
    private final String TAG_VIP_MONEY = "TAG_VIP_MONEY";
    private ActivityVipShopExchangeBinding binding;
    private VipExchangeConstract.VipExchangePresenter presenter;
    private MultiTypeAdapter multiTypeAdapter;
    private String money;
    private User userInfo;
    private Dialog dialog; // loading dialog
    private VipExchangeMoneyModel selectedExchangeType;
    private ExchangeVerificationService exchangeVerificationService;

    public static void startActivity(Context context) {
        checkLogin(context, new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, VipExchangeActivity.class);
                context.startActivity(intent);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_vip_shop_exchange);
        presenter = new VipExchangeConstract.VipExchangePresenter();
        if (savedInstanceState != null) {
            money = savedInstanceState.getString(TAG_VIP_MONEY);
            selectedExchangeType = savedInstanceState.getParcelable(TAG_VIP_SELECTED_MONEY_TYPE);
        }
        ToolbarManager.setToolbar(this, binding.toolbar);
        initViews();
        initEvents();
        initData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(TAG_VIP_MONEY, money);
        outState.putParcelable(TAG_VIP_SELECTED_MONEY_TYPE, selectedExchangeType);
        super.onSaveInstanceState(outState);
    }

    private void initViews() {
        ChipsLayoutManager layoutManager = ChipsLayoutManager.newBuilder(this)
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                .build();
        multiTypeAdapter = new MultiTypeAdapter();
        multiTypeAdapter.register(VipExchangeMoneyModel.class, new VipExchangeViewBinder(this));
        binding.exchangeMoneyTags.setLayoutManager(layoutManager);
        binding.exchangeMoneyTags.setAdapter(multiTypeAdapter);
    }

    private void initEvents() {
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.exchange)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        // todo :
                        if (Float.valueOf(money) <= 0) {
                            ToastManager.show(VipExchangeActivity.this.getApplicationContext(), "无可兑换金额");
                            return;
                        }
                        if (selectedExchangeType.getMoney() > Float.valueOf(money)) {
                            ToastManager.show(VipExchangeActivity.this.getApplicationContext(), "可兑换金额不足");
                            return;
                        }
                        exchangeVerificationService.check(VipExchangeActivity.this);
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getVipExchangableMoney(userInfo);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_help_vip, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_help:
                KyeWebActivity.startActivity(this, "https://res.ky-express.com/h5/help/56.html", "帮助", false);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initData() {
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        exchangeVerificationService = new ExchangeVerificationService(user.getPhone(), 3);
        exchangeVerificationService.setProvider(getProvider());
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void getVipExchangbleMoneySuccess(String money) {
        this.money = money;
        binding.statusLayout.showContentView();
        binding.exchangeMoney.setText(String.format("¥%s", money));
        initExchangeMoneyTags();
    }

    private void initExchangeMoneyTags() {
        List<VipExchangeMoneyModel> dataList = VipExchangeMoneyModel.createDataList(getApplicationContext());
        multiTypeAdapter.setItems(dataList);
        multiTypeAdapter.notifyDataSetChanged();
    }

    @Override
    public void getVipExchangbleMoneyServerFailed(String msg) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(getApplicationContext(), msg);
    }

    @Override
    public void getVipExchangbleMoneyNetFailed(String message) {
        binding.statusLayout.showErrorNetworkView();
        ToastManager.show(getApplicationContext(), message);
    }

    @Override
    public void OnItemClicked(VipExchangeMoneyModel item) {
        selectedExchangeType = item;
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }

    @Override
    public void getPictureCodeSuccess(byte[] picture) {

    }

    @Override
    public void onSendSmsCodeSuccess() {

    }

    @Override
    public void onCannotExchangeError(String msg) {
        // todo : 跳转人气支持
        ToastManager.show(getApplicationContext(), msg);
    }

    @Override
    public void onNeedSendSmsError(String msg, String smsChannel, String type, String phone) {
        // todo :
        exchangeVerificationService.showVerificationByAutoSendMessage(this, 4, phone, smsChannel, this);
    }

    @Override
    public void onAccountError(String msg, String smsChannel, String type, String phone) {
        ToastManager.show(getApplicationContext(), msg);
    }

    @Override
    public void onOpenApiError(OpenApiResult openApiResult) {
        ToastManager.show(getApplicationContext(), openApiResult.getMsg());
    }

    @Override
    public void onOtherError(Throwable e) {
        ToastManager.show(getApplicationContext(), e.getMessage());
    }

    @Override
    public void onVerifyByAutoSendMessage(String smsChannel, String type, String phone) {
        exchangeVerificationService.showVerificationByAutoSendMessage(this, 4, phone, smsChannel, this);
    }

    @Override
    public void onVerifyByPictureSms(String smsChannel, String type, String phone) {
        exchangeVerificationService.showVerificationByPictureSmsDialog(this, 4, this);
    }

    @Override
    public void toExchange1(String smsCodeInput, MaterialDialog mDialog) {
        presenter.exchange(userInfo, selectedExchangeType, money, smsCodeInput, mDialog);
    }

    @Override
    public void toExchange2(String smsCodeInput, MaterialDialog mDialog) {
        presenter.exchange(userInfo, selectedExchangeType, money, smsCodeInput, mDialog);
    }

    @Override
    public void exchangeSuccess(VipExchangeResultBean vipExchangeResultBean, MaterialDialog mDialog) {
        mDialog.dismiss();
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void exchangeServerFailed(String msg) {
        ToastManager.show(getApplicationContext(), msg);
    }

    @Override
    public void exchangeNetFailed(String message) {
        ToastManager.show(getApplicationContext(), message);
    }
}
